package cc.yiueil.handler;

import cc.yiueil.entity.UserEntity;
import cc.yiueil.utils.JwtUtils;
import cc.yiueil.vo.ResultVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;

@Component
public class ApplicationLoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    ObjectMapper objectMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        // 签发JWT
        HashMap<String, Object> claims = new HashMap<>();
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername(authentication.getName());
        userEntity.setAuthorities(authentication.getAuthorities());
        claims.put("user", objectMapper.writeValueAsString(userEntity));
        String jwt = JwtUtils.generateToken(Collections.emptyMap(), claims);
        response.getWriter().write(objectMapper.writeValueAsString(ResultVo.success(jwt)));
    }
}
